from application.mapper.FavoriteMapper import FavoriteMapper
from application.mapper.NoteMapper import NoteMapper
from application.model.FavoriteModel import FavoriteModel
from application.logic.NoteLogic import get_note_by_id
from application.enumeration.ContentTypeEnum import ContentTypeEnum
from application.exception.BasicException import BasicException
from application.enumeration.StatusCodeEnum import StatusCodeEnum
from application.model.NoteModel import NoteModel
from typing import Optional


async def add_favorite(user_id: int, target_id: int, content_type: ContentTypeEnum) -> None:
    """
    添加收藏
    :param user_id: 当前用户ID
    :param target_id: 目标ID
    :param content_type: 收藏类型
    :return:
    """
    # 检查收藏内容
    note_model: Optional[NoteModel] = await NoteMapper.get_data_by_id(data_id=target_id)
    if not note_model or note_model.is_disabled:
        raise BasicException(status_code=StatusCodeEnum.NOT_FOUND_ERROR, message="收藏的内容不存在或已被封禁！")
    # 检查是否已收藏
    if await FavoriteMapper.get_data_by_field(user_id=user_id, target_id=target_id):
        raise BasicException(status_code=StatusCodeEnum.ALREADY_EXIST_ERROR, message="该内容已收藏！")
    # 添加收藏
    if not await FavoriteMapper.insert(data={
        "user_id": user_id,
        "target_id": target_id,
        "content_type": content_type
    }):
        raise BasicException(status_code=StatusCodeEnum.ERROR, message="添加收藏失败！")


async def delete_favorite_by_id(favorite_id: int) -> None:
    """
    根据ID删除收藏
    :param favorite_id: 收藏ID
    :return:
    """
    # 检查收藏
    model: FavoriteModel = await FavoriteMapper.get_data_by_id(data_id=favorite_id)
    if not model:
        raise BasicException(status_code=StatusCodeEnum.NOT_FOUND_ERROR, message="该收藏不存在！")
    # 删除收藏
    if not await FavoriteMapper.delete(orm_model=model):
        raise BasicException(status_code=StatusCodeEnum.ERROR, message="删除收藏失败！")


async def get_list_by_user_id(user_id: int, content_type: ContentTypeEnum, page: int, page_size: int) -> list:
    """
    根据用户ID获取收藏列表
    :param user_id: 用户ID
    :param content_type: 收藏内容类型
    :param page: 页码
    :param page_size: 每页数量
    :return: 收藏列表
    """
    favorite_model_list: list = await FavoriteMapper.get_data_list(page=page, page_size=page_size, user_id=user_id,
                                                                   content_type=content_type)
    result: list = []
    for favorite_model in favorite_model_list:
        # 如果是帖子，处理帖子输出
        if content_type == ContentTypeEnum.NOTE:
            result.append(await get_note_by_id(note_id=favorite_model.target_id))
    return result
